package dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerUtils {
	private static EntityManagerFactory emf=Persistence.createEntityManagerFactory("myjpa");
	private static final ThreadLocal<EntityManager> threadlocal=new ThreadLocal<EntityManager>();
	
	public static EntityManagerFactory getFactory() {
		return emf;
	}
	
	public static EntityManager getEntityManager() {
		EntityManager entityManager=(EntityManager)threadlocal.get();
		if(entityManager==null) {
			entityManager=emf.createEntityManager();
			threadlocal.set(entityManager);
		}
		return entityManager;
	}
	
	public static void closeEntityManager() {
		EntityManager entityManager=threadlocal.get();
		if(entityManager!=null) {
			entityManager.close();
			threadlocal.set(null);
		}
	}
	
	public static void shutdown() {
		getFactory().close();
	}
}
